/*
 * @(#)StandardTextExtractor.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.extractor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import com.dcivision.framework.CharsetDetector;
import com.snowtide.commons_logging.Log;
import com.snowtide.commons_logging.LogFactory;

/**
 * StandardTextExtractor.java
 * 
 * This class is the text extractor for unkown files.
 * 
 * @author Rollo Chan
 * @company DCIVision Limited
 * @creation date 26/08/2003
 * @version $Revision: 1.10.2.5 $
 */

public class StandardTextExtractor extends AbstractTextExtractor {

  public static final String REVISION = "$Revision: 1.10.2.5 $";

  private static final Log log = LogFactory.getLog(StandardTextExtractor.class);

  public StandardTextExtractor(InputStream fis, String encoding) {
    super(fis, encoding);
    Reader reader = null;
    File tmpFile = null;
    try {
      tmpFile = File.createTempFile(com.dcivision.framework.Utility.getCurrentTimestamp().getTime() + "", ".txt");
      FileOutputStream fos = new FileOutputStream(tmpFile);
      int i = -1;
      while ((i = fis.read()) != -1) {
        fos.write(i);
      }
      try {
        fos.close();
      } catch (Exception ignore) {
      } finally {
        fos = null;
      }

      InputStream tmpIS = new FileInputStream(tmpFile);
      String newEncoding = CharsetDetector.getCharset(tmpIS);
      if (newEncoding.equals("nomatch"))
        newEncoding = encoding;
      tmpIS.close();

      fis = new FileInputStream(tmpFile);
      reader = new BufferedReader(new InputStreamReader(fis, newEncoding));
      StringBuffer sb = new StringBuffer();
      i = -1;
      while ((i = reader.read()) != -1) {
        sb.append((char) i);
      }
      text = sb.toString();
    } catch (Exception e) {
      log.error("Error Info",e);
    } finally {
      try {
        reader.close();
      } catch (Exception ignore) {
      } finally {
        reader = null;
      }
      tmpFile.delete();
    }
  }

}